package com.szewec.ps.myview.recordsound;

import android.app.Activity;
import android.app.Dialog;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.szewec.ps.base.Constants;

import com.szewec.ps.R;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class RecordSoundDialog extends Dialog {
    private Activity mActivity;
    /**
     * 状态:1-录音未开始 2-录音中 3-播放未开始 4-播放中 5-暂停中
     */
    private Integer mStatus;
    /**
     * 操作类型:1-录音 2-播放录音
     */
    private Integer mActionFlag;
    /**
     * 录音文件的路径
     */
    private String mFilePath;
    /**
     * 播放器
     */
    private MediaPlayer mediaPlayer;
    /**
     * 录音器
     */
    private MediaRecorder mediaRecorder;

    private ImageView ivDb;
    private TextView tips;
    private StopedClickedListener stopedClickedListener;
    private List<Integer> temp;
    private ScaleAnimation scaleAnimation;
    /**
     * 计时器
     */
    private Timer mTimer;
    /**
     * 计时任务
     */
    private TimerTask mTimerTask;
    private long seconds;


    public interface StopedClickedListener{
        void onStopClicked();
    }

    public RecordSoundDialog(Activity activity, int themeResId,Integer actionFlag,String filePath,StopedClickedListener listener) {
        super(activity, themeResId);
        mActivity = activity;
        mActionFlag = actionFlag;
        stopedClickedListener = listener;
        mFilePath = filePath;
        if (actionFlag == 1){
            mStatus = 1;
        }else {
            mStatus = 4;
        }

        setCanceledOnTouchOutside(false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View view = getLayoutInflater().inflate(R.layout.record_sound_dialog,
                null);
        setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = getWindow();

        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = mActivity.getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        // 设置显示位置
        onWindowAttributesChanged(wl);

        initViews();

        if (mActionFlag == 1){
            initRecorder();
        }else {
            initPlayer();
        }
    }

    private void initViews(){
        ImageView ivClose = findViewById(R.id.iv_close);
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doDestroy();
                dismiss();
            }
        });

        ImageView ivAction = findViewById(R.id.iv_action);
        tips = findViewById(R.id.tip);
        ivDb = findViewById(R.id.iv_db);
        if (mActionFlag == 1){

        }else {
            ivAction.setBackground(mActivity.getResources().getDrawable(R.drawable.pause));
        }
        ivAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (mStatus){
                    case Constants.RecordSoundStatus.RECORD_UNSTART:
                        //开始录音
                        mStatus = Constants.RecordSoundStatus.RECORDING;
                        ivAction.setBackground(mActivity.getResources().getDrawable(R.drawable.stop));
                        try {
                            // 准备好开始录音
                            mediaRecorder.prepare();
                            mediaRecorder.start();
                            temp = new ArrayList<>();
                            mTimer = new Timer();
                            mTimer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    db(mediaRecorder.getMaxAmplitude());
                                }
                            },0,100);
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case Constants.RecordSoundStatus.RECORDING:
                        //结束录音,保存退出
                        doDestroy();
                        stopedClickedListener.onStopClicked();
                        dismiss();
                        break;
                    case Constants.RecordSoundStatus.PLAY_UNSTART:
                    case Constants.RecordSoundStatus.PAUSE:
                        //开始播放录音
                        mTimer = new Timer();
                        mTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                updatePlayTime();
                            }
                        },1000,1000);
                        mStatus = Constants.RecordSoundStatus.PLAYING;
                        ivAction.setBackground(mActivity.getResources().getDrawable(R.drawable.pause));
                        mediaPlayer.start();
                        break;
                    case Constants.RecordSoundStatus.PLAYING:
                        //暂停播放
                        mTimer.cancel();
                        mStatus = Constants.RecordSoundStatus.PAUSE;
                        ivAction.setBackground(mActivity.getResources().getDrawable(R.drawable.play));
                        mediaPlayer.pause();
                        break;
                }
            }
        });
    }

    private void db(int db){
        temp.add(db);
        if (temp.size() >= 5){
            BigDecimal b = new BigDecimal(Collections.max(temp)).divide(new BigDecimal(30000),3,BigDecimal.ROUND_HALF_UP);
            float f = 1 + b.floatValue();
            //防止超大
            if (f > 2){
                f = 2;
            }
            scaleAnimation = new ScaleAnimation(1f,f,1f,f, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
            scaleAnimation.setDuration(500);
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ivDb.startAnimation(scaleAnimation);
                }
            });
            temp.clear();
        }
        seconds = seconds + 100;
        if (seconds % 1000 == 0){
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tips.setText(getFormatHMS(seconds));
                }
            });
        }

    }

    private void updatePlayTime(){
        seconds = seconds + 1000;
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tips.setText(getFormatHMS(seconds) + "/" + getFormatHMS(mediaPlayer.getDuration()));
            }
        });
    }

    private void initRecorder(){
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
        mediaRecorder.setOutputFile(mFilePath);
    }

    private void initPlayer(){
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(mFilePath);
        }catch (IOException e){
            e.printStackTrace();
        }
        mediaPlayer.setLooping(false);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();
                mTimer = new Timer();
                mTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        updatePlayTime();
                    }
                },1000,1000);
            }
        });
        mediaPlayer.prepareAsync();

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer paramMediaPlayer) {
                doDestroy();
                dismiss();
            }
        });
    }

    public String getFormatHMS(long time) {
        time = time / 1000;//总秒数
        int s = (int) (time % 60);//秒
        int m = (int) (time / 60) % 60;//分
        int h = (int) (time / 3600) % 60;//小时
        return String.format("%02d:%02d:%02d", h, m, s);
    }

    private void doDestroy(){
        if (mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
        if (mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer = null;
        }
        if (mediaRecorder != null){
            try {
                mediaRecorder.stop();
            }catch (IllegalStateException e){
            }
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }
}
